//有三个线程，分别只能打印A，B和C
//要求按顺序打印ABC，打印10次
public class Thread4 {
    private static Object o = new Object();

    private static int flag; //0 A, 1 B ,2 C

    public static void main(String[] args) {
        Thread A = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                synchronized (o){
                    while (flag != 0){
                        try {
                            o.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.print("A");
                    flag = 1;
                    o.notifyAll();
                }
            }
        });
        Thread B = new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                synchronized (o) {
                   while (flag != 1){
                       try {
                           o.wait();
                       } catch (InterruptedException e) {
                           throw new RuntimeException(e);
                       }
                   }
                    System.out.print("B");
                    flag = 2;
                    o.notifyAll();
                }
            }
        });
        Thread C = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                synchronized(o){
                   while (flag !=2){
                       try {
                           o.wait();
                       } catch (InterruptedException e) {
                           throw new RuntimeException(e);
                       }
                   }
                    System.out.println("C");
                    flag = 0;
                    o.notifyAll();
                }
            }
        });

        A.start();
        B.start();
        C.start();
    }
}
